<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生管理系统</title>
</head>
<body>
  <h2>学生列表</h2>
  <table>
    <thead>
      <tr>
        <th>学生姓名</th>
        <th>学生年龄</th>
        <th>学生性别</th>
        <th>学生操作</th>
      </tr>
    </thead>

    <tbody>
      
    </tbody>
  </table>

  <script src="./js/jquery.min.js"></script>

  <script>
    getStudents()
    function getStudents () {
      $.ajax({
        url: '/student/getStudents',
        type: 'get',
        success(res) {
          if (res.status === 200) {
            let str = ''
            res.data.forEach((item, index) => {
              str += (`
              <tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.gender}</td>
                <td>
                  <button>修改</button>
                  <button data-id="${item.id}" class="removeBtn">删除</button>
                </td>
              </tr>
              `)
            })
            $('tbody').html(str)
          } else {
            alert(res.msg)
          }
        }
      })
    }

    // 事件委托：将子元素想要执行的事件，委托给父元素去绑定
    $('tbody').on('click', '.removeBtn', function () {
      const id = $(this).data('id')
      $.ajax({
        url: '/student/delStudents',
        type: 'delete',
        data: {
          id: id
        },
        success(res) {
          if (res.status) {
            alert('删除成功!')
            getStudents()
          } else {
            console.log('删除失败');
          }
        }
      })
    })
  </script>
</body>
</html>